package com.fang.mybatis;

import com.fang.bean.A;
import com.fang.mybatis.mapper.AMapper;
import org.apache.ibatis.annotations.Select;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author fanglingxiao
 * @version 1.0
 * @description TODO
 * @date 2022/4/5 6:24 下午
 **/
public class Test {
    public static void main(String[] args) {
        AMapper aMapper = (AMapper) Proxy.newProxyInstance(Test.class.getClassLoader(), new Class[]{AMapper.class}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                // 解析参数
                Map<String, Object> params = parseArgs(method, args);
                Select select = method.getAnnotation(Select.class);
                // 解析sql语句
                String sql = parseSql(select.value()[0], params);
                return null;
            }
        });
        A a = aMapper.selectOne(1, 1);
        System.out.println(a);
    }

    private static String parseSql(String sql, Map<String, Object> params) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < sql.length(); i++) {
            char c = sql.charAt(i);
            if (c == '#') {
                int paramIndex = i + 1;
                if (sql.charAt(paramIndex) != '{') {
                    throw new RuntimeException("sql parse error");
                }
                StringBuilder paramSb = new StringBuilder();
                while (true) {
                    paramIndex++;
                    if (sql.charAt(paramIndex) == '}') {
                        break;
                    }
                    sb.append(sql.charAt(paramIndex));
                }

            }
        }
        return null;
    }

    private static Map<String, Object> parseArgs(Method method, Object[] args) {
        Map<String, Object> params = new HashMap<>(16);
        // 获取方法参数
        Parameter[] parameters = method.getParameters();
        int[] index = {0};
        // 组装
        Arrays.asList(parameters).forEach(parameter -> {
            params.put(parameter.getName(), args[index[0]]);
            index[0]++;
        });
        return params;
    }
}
